package com.baiwang.web.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class TestCase {
  private static String apiName = "baiwang.output.redinvoice.add";             //API名称
  private static String appKey = "1002539";                                 //appKey
  private static String appSecret = "7df54c16-e899-4f99-9e71-354ca2ee6b8f";  //appSecret
  // private static String token = "060eda36-d148-4731-bb26-e6f0fd0d4d98";      //token

  private static final ObjectMapper mapper = new ObjectMapper();

  public static void main(String[] args) throws Exception {
    Map<String, String> textParams = new HashMap<String, String>();
    // 添加协议级请求参数
    textParams.put("method", apiName);
    textParams.put("version", "6.0");
    textParams.put("appKey", appKey);
    textParams.put("format", "json");
    textParams.put("timestamp", "1567135658634");
    // textParams.put("token", token);
    textParams.put("type", "sync");

    String requestBody = "{\"taxNo\":\"980888\",\"mallId\":\"1234567\"," +
            "\"mallName\":\"\",\"apiName\":\"baiwang.ec.mall.taxnostatus\"," +
            "\"textParams\":{\"mallId\":\"1234567\",\"taxNo\":\"980888\"}}";

    String signString = signTopRequest(textParams, appSecret, requestBody);  //签名参数
    System.out.println(signString);
  }

  /**
   * 给TOP请求签名。
   *
   * @param params 所有字符型的TOP请求参数
   * @param secret 签名密钥
   * @return 签名
   * @throws Exception
   */
  public static String signTopRequest(Map<String, String> params,
                                      String secret,
                                      String body) throws Exception {
    // 第一步：检查参数是否已经排序
    ArrayList<String> keys = new ArrayList<String>(params.keySet());
    Collections.sort(keys);
    // 第二步：把所有参数名和参数值串在一起
    StringBuilder query = new StringBuilder();
    query.append(secret);
    for (String key : keys) {
      String value = params.get(key);
      if (!isNull(key) && !isNull(value)) {
        query.append(key).append(value);
      }
    }

    JsonNode node = mapper.readTree(body);
    body = mapper.writeValueAsString(node);
    query.append(body);

    query.append(secret);
    // 第三步：使用MD5加密
    byte[] bytes;
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException ignored) {
      throw new Exception(ignored);
    }

    bytes = md5.digest(query.toString().getBytes("UTF-8"));
    // 第四步：把二进制转化为大写的十六进制
    StringBuilder sign = new StringBuilder();
    for (byte b : bytes) {
      String hex = Integer.toHexString(b & 0xFF);
      if (hex.length() == 1) {
        sign.append("0");
      }
      sign.append(hex.toUpperCase());
    }
    return sign.toString();
  }

  public static boolean isNull(String str) {
    return (str == null || "".equals(str) ? true : false);
  }
}